package org.example.shop_front_api.controller;

import org.example.shop_front_api.entity.ESGoods;
import org.example.shop_front_api.entity.ESNews;
import org.example.shop_front_api.entity.Goods;
import org.example.shop_front_api.service.GoodsService;
import org.example.shop_front_api.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.highlight.Highlight;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightField;
import org.springframework.data.elasticsearch.core.query.highlight.HighlightParameters;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("api/goods")
public class GoodsController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ESGoods esGoods;
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;
    @PostMapping("add")
    public JsonResult add(@RequestBody Goods goods) {
        int result = goodsService.addGoods(goods);
        if (result == 0) {
            JsonResult.failed("添加失败");
        }
        //同步到es
        esGoods.setId(goods.getId());
        esGoods.setGoodsName(goods.getGoodsName());
        esGoods.setFirstCateId(goods.getFirstCateId());
        esGoods.setSecondCateId(goods.getSecondCateId());
        esGoods.setThirdCateId(goods.getThirdCateId());
        esGoods.setSalesNumber(goods.getSalesNumber());
        esGoods.setSalePrice(goods.getSalePrice());
        esGoods.setMainImage(goods.getMainImage());
        elasticsearchOperations.save(esGoods);

        return JsonResult.success("添加成功",null);
    }

    @GetMapping("list")
    public JsonResult list(@RequestParam("cate_id") int cateId ,
                           @RequestParam("level") int level) {
        List<Goods> goodsList = goodsService.getGoodsByCateId(cateId, level);
        return JsonResult.success("获取成功",goodsList);
    }

    @GetMapping("search")
    public JsonResult search(@RequestParam("keyword") String keyword,
                             @RequestParam("cate_id") int cateId,
                             @RequestParam("level") int level,
                             @RequestParam("order_by") String orderBy
    ) {

        // 创建高亮配置
        HighlightField highlightField = new HighlightField("goods_name");
        HighlightParameters parameters = HighlightParameters.builder()
                .withPreTags("<span style='color: red'>")
                .withPostTags("</span>")
                .withFragmentSize(Integer.MAX_VALUE)
                .withNumberOfFragments(1)
                .build();


        Highlight highlight = new Highlight(parameters, List.of(highlightField));
        HighlightQuery highlightQuery = new HighlightQuery(highlight, ESNews.class);


        NativeQuery query = null;
        if(keyword != null && !keyword.isEmpty()) {
            query = NativeQuery.builder()
                    .withQuery(q -> q
                            .match(m -> m
                                    .field("goods_name")
                                    .query(keyword)
                            )
                    )
                    .withHighlightQuery(highlightQuery)
                    .withPageable(
                            PageRequest.of(0, 10,
                                    Sort.by(
                                            Sort.Order.desc(orderBy)
                                    )
                            )
                    )
                    .build();
        } else {
            if (cateId !=0) {
                if (level == 1) {
                    System.out.println(cateId);
                    query = NativeQuery.builder()
                            .withQuery(q -> q
                                    .match(m -> m
                                            .field("first_cate_id")
                                            .query(cateId)
                                    )
                            )
                            .withPageable(
                                    PageRequest.of(0, 10,
                                            Sort.by(
                                                    Sort.Order.desc(orderBy)
                                            )
                                    )
                            )
                            .build();
                }
                if (level == 2) {
                    query = NativeQuery.builder()
                            .withQuery(q -> q
                                    .match(m -> m
                                            .field("second_cate_id")
                                            .query(cateId)
                                    )
                            )
                            .withPageable(
                                    PageRequest.of(0, 10,
                                            Sort.by(
                                                    Sort.Order.desc(orderBy)
                                            )
                                    )
                            )
                            .build();
                }

                if (level == 3) {
                    query = NativeQuery.builder()
                            .withQuery(q -> q
                                    .match(m -> m
                                            .field("third_cate_id")
                                            .query(cateId)
                                    )
                            )
                            .withPageable(
                                    PageRequest.of(0, 10,
                                            Sort.by(
                                                    Sort.Order.desc(orderBy)
                                            )
                                    )
                            )
                            .build();
                }
            }
        }
        SearchHits<ESGoods> searchHits = elasticsearchOperations.search(query, ESGoods.class);
        HashMap<String, Object> resultData = new HashMap<>();
        resultData.put("hits", searchHits.getSearchHits());
        resultData.put("totalHits", searchHits.getTotalHits());
        return JsonResult.success("搜索成功",resultData);
    }
}
